import datasetService from '@/api/services/datasetService';
import { MAX_NAME_LENGTH } from '@/common';
import Modals from '@/components/modals/Modals';
import { Input, message } from 'antd';
import { useEffect, useState } from 'react';
import { useContextSelector } from 'use-context-selector';
import { DatasetsContext } from '../../context';

interface UpdateNameModalProps {
  isDatasetModalVisible: boolean;
  setIsDatasetModalVisible: (visible: boolean) => void;
  updateNode: any;
}

export default function UpdateNameModal({
  isDatasetModalVisible,
  setIsDatasetModalVisible,
  updateNode,
}: UpdateNameModalProps) {
  const [newDatasetName, setNewDatasetName] = useState('');
  const [messageApi, contextHolder] = message.useMessage();
  const { setSelectedTreeNode, setSelectedTreeData, selectedTreeData } = useContextSelector(
    DatasetsContext,
    (s) => s,
  );

  

  const datasetRename = async () => {
    if (!newDatasetName) {
      messageApi.error('名称不能为空');
      return;
    }
    if (newDatasetName.length > MAX_NAME_LENGTH) {
      messageApi.error(`名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    const data = {
      ...updateNode,
      name: newDatasetName,
    };
    try {
      await datasetService.updateKnowledgeBase(data);
      messageApi.success('修改成功');
      setIsDatasetModalVisible(false);
      
      const updatedTreeData = selectedTreeData.map((node) =>
        node.id === updateNode.dataset_id
          ? { ...node, name: newDatasetName, title: newDatasetName }
          : node,
      );
      console.log(data);
      const newdata = {...data,id :data.dataset_id }
      
      setSelectedTreeNode(newdata);
      setSelectedTreeData(updatedTreeData);
    } catch (error) {
      console.log(error);
      messageApi.error('修改失败');
    }
  };

  useEffect(() => {
    setNewDatasetName(updateNode?.name);
  }, [updateNode]);

  return (
    <div>
      {contextHolder}
      <Modals
        title={
          <div style={{ textAlign: 'center', width: '100%' }}>
            {updateNode?.type == 'dataset'
              ? '知识库'
              : updateNode?.type == 'file'
              ? '文档'
              : '文件夹'}
            重命名
          </div>
        }
        open={isDatasetModalVisible}
        onOk={datasetRename}
        onCancel={() => {
          setIsDatasetModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newDatasetName} onChange={(e) => setNewDatasetName(e.target.value)} />
        </div>
      </Modals>
    </div>
  );
}
